﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSharp.Libs.WPF;
using System.Timers;
using System.Reflection;
using System.IO;
using CSharp.Libs.Koc.KernelModels.ItemClasses;

namespace CSharp.Libs.Koc.UserControls
{
    class KocStatisticsViewModel : ViewModelBase
    {
        #region declarations
        private Kernel _KRNL = null;

        private Timer _tmrStatsLog = null;

        private Boolean _fLogToCsvFile = true;
        private Int64 _intTimerInterval = 900000; //Standard Interval = 15m * 60s * 1.000ms = 900.000ms
        private String _strFilePath = "";
        private String _strLogFileNameCsv = "KocStatistics.csv";
        private String _strCompleteCsvFile = "";

        private const Int64 TIMER_INTERVAL_MIN = 5000;//Minimum Interval = 5s * 1.000ms = 5.000ms
        private const Int64 TIMER_INTERVAL_MAX = 86400000;//Maximum Interval = 24h * 60m * 60s * 1000ms = 86.400.000ms
        private const String CSV_FORMAT = "{0};{1};{2};{3};{4};{5};{6};{7}";
        #endregion



        #region constructor / terminator
        public KocStatisticsViewModel(
            Kernel KRNL)
        {
            _KRNL = KRNL;

            _tmrStatsLog = new Timer(_intTimerInterval);
            _tmrStatsLog.Elapsed += new ElapsedEventHandler(_tmrStatsLog_Elapsed);

            //Get Path of current executable
            _strFilePath = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;
        }

        ~KocStatisticsViewModel()
        {
            _tmrStatsLog = null;
        }
        #endregion



        #region event handling
        void _tmrStatsLog_Elapsed(object sender, ElapsedEventArgs e)
        {
            _tmrStatsLog.Enabled = false;
            _LogStatistics();
            _tmrStatsLog.Enabled = true;
        }
        #endregion

        
        
        #region private functions
        /// <summary>_LogStatistics</summary>
        /// <history>18.07.2011</history>
        private void _LogStatistics()
        {
            try
            {
                if(_fLogToCsvFile)
                {
                    _LogToCsvFile();
                    _ReadCsvFile();
                }
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }
        }

        /// <summary>_LogToCsvFile</summary>
        /// <history>18.07.2011</history>
        private void _LogToCsvFile()
        {
            try
            {
                //generate FileName
                String strFullFileName = String.Concat(_strFilePath, "\\", _strLogFileNameCsv);
                String strWriteDate = DateTime.Now.ToString(constants.DATE_TIME_STAMP_MASK_LOG_ENTRY);
                String strHeader = String.Format(CSV_FORMAT, "CityID", "CityName", "DateTime", "Usage", "Food", "Wood", "Stone", "Ore");
                Boolean fWriteHeader = false;

                if(!File.Exists(strFullFileName))
                {
                    fWriteHeader = true;
                }

                FileStream FS = new FileStream(strFullFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter SW = new StreamWriter(FS);
                
                if(fWriteHeader)
                {
                    SW.WriteLine(strHeader);    
                }

                FS.Position = FS.Length;

                foreach(SeedCityItem SCI in _KRNL.BSVM.Cities)
                {
                    SW.WriteLine(String.Format(CSV_FORMAT,
                        SCI.CityID.ToString(),
                        SCI.CityName,
                        strWriteDate,
                        (SCI.Resources.Food.Usage - SCI.Resources.Food.Production).ToString(),
                        SCI.Resources.Food.Value.ToString(),
                        SCI.Resources.Wood.Value.ToString(),
                        SCI.Resources.Stone.Value.ToString(),
                        SCI.Resources.Ore.Value.ToString()));
                }

                SW.Flush();
                SW.Close();
                SW.Dispose();
                SW = null;

                FS.Dispose();
                FS = null;
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }
        }

        /// <summary>_ReadCsvFile</summary>
        /// <history>18.07.2011</history>
        private void _ReadCsvFile()
        {
            try
            {
                //generate FileName
                String strFullFileName = String.Concat(_strFilePath, "\\", _strLogFileNameCsv);

                if(File.Exists(strFullFileName))
                {
                    _strCompleteCsvFile = "";

                    FileStream FS = new FileStream(strFullFileName, FileMode.Open, FileAccess.Read);
                    StreamReader SR = new StreamReader(FS);

                    while(!SR.EndOfStream)
                    {
                        _strCompleteCsvFile = String.Concat(_strCompleteCsvFile, SR.ReadLine(), Environment.NewLine);
                    }
                    OnPropertyChanged("CompleteCsvFile");

                    SR.Close();
                    SR.Dispose();
                    SR = null;

                    FS.Dispose();
                    FS = null;
                }
            }
            catch(Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }
        }
        #endregion



        #region interface
        #region properties
        public Boolean LogStatisticsEnabled
        {
            get
            {
                return _tmrStatsLog.Enabled;
            }
            set
            {
                _tmrStatsLog.Enabled = value;
            }
        }

        public Int64 TimerInterval
        {
            get
            {
                return (Int64)_tmrStatsLog.Interval;
            }
            set
            {
                if (value >= TIMER_INTERVAL_MIN &&
                    value <= TIMER_INTERVAL_MAX)
                {
                    _tmrStatsLog.Interval = (Double)value;
                }

                OnPropertyChanged("TimerInterval");
            }
        }

        public String FilePath
        {
            get
            {
                return _strFilePath;
            }
            set
            {
                _strFilePath = value;
            }
        }

        public Boolean LogToCsvFile
        {
            get
            {
                return _fLogToCsvFile;
            }
            set
            {
                _fLogToCsvFile = value;
            }
        }

        public String FileNameCsv
        {
            get
            {
                return _strLogFileNameCsv;
            }
            set
            {
                _strLogFileNameCsv = value;
            }
        }

        public String CompleteCsvFile
        {
            get
            {
                return _strCompleteCsvFile;
            }
        }
        #endregion

        #region methods
        #endregion
        #endregion
    }
}
